import React from 'react';
import { Input, Button, Select,  Form,  DatePicker, Table, Collapse,  message ,Modal} from 'antd';
import config from '../../config/config';
import $ from 'jquery';
const allRouter = config.router;
const Panel = Collapse.Panel;
const token = sessionStorage.getItem('token');
class AssistantTherapyDetails extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            patientInfo: [],//该患者信息
            date: undefined, // 时间
            data1:'',//时间字符串
            allOrderDetails:[],//所有就诊订单信息
            storeName:'',//门店的名字
        }
    }
    componentWillMount() {

        //获取该患者信息
        this.getThisPatientInfo();
        this.getPatientOrders();

    }
    componentDidMount() {
        console.log();
    }
    // 获取该患者信息
    getThisPatientInfo() {
        let url = allRouter.patientOrigin + '/patient/one/' + this.props.params.patientId;
        $.ajax({
            url: url,
            type: "get",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success: data => {
                 console.log('该患者基本信息');
                 console.log(data);
                if (data.code === 200) {
                    this.setState({
                        patientInfo: data.data
                    })
                } else {
                    console.log("获取该患者信息出错");
                }
            },
            error: err => {
                console.log(err);
            }
        })
    }
    //获取该患者所有订单信息
    getPatientOrders(starttime,endtime){
        let url = allRouter.patientOrigin +'/surgicalTreatment/particulars';
        $.ajax({
            url: url,
            type: "POST",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                patient_id:this.props.params.patientId,
                starttime,
                endtime,
            },
            success: data => {
                console.log('该患者所有订单信息');
                console.log(data);
               if(data.data){
                   data.data.map((item,i)=>{
                       item.index=i;
                       item.chargeschedule.map((item1,j)=>{
                           //1：开始治疗 2：完成治疗  3：已完成   4：开始治疗  ,5:已退费
                           if(item1.p_refundstate){
                               item1.isTraiging=5;
                           }else{
                               if(item1.p_paystate===1||item1.p_paystate===3){
                                       item1.isTraiging=4;
                               }
                               if(item1.p_paystate===2){
                                   if(item1.p_servedNumber===item1.p_Number){
                                       item1.isTraiging=3;
                                   }else{
                                       if(item1.serveState&&item1.serveState===2){
                                           item1.isTraiging=2;
                                       }else{
                                           item1.isTraiging=1;
                                       }
                                   }
                               }
                           }

                           item1.index=j;
                           item1.parentId=item._id;
                           item1.orderID=item.orderid;
                           item1.parentIndex=i;
                       });
                   });
               }

                if (data.code === 200) {
                    this.setState({
                        allOrderDetails:data.data
                    },()=>{
                        console.log('fsdshdjhdysre');
                        console.log(this.state.allOrderDetails);
                        if(this.state.allOrderDetails.length)
                        this.getStoreList(this.state.allOrderDetails[0].clinicname)
                    })
                } else {
                    message.info("获取该患者订单出错,请返回重新操作");
                }
            },
            error: err => {
                console.log(err);
            }
        })
    }
    // 日期
    changeDate(date, str) {
        console.log(date);
        this.setState({
            date,
            data1:str
        });
        this.getPatientOrders(str,str);
    }
    //禁用今天以后的日期
    disabledDate(val) {
        if (val) {
            return val.valueOf() > Date.now();
        } else {
            return false;
        }
    }

    //获取门店列表
    getStoreList(id) {
        let url=allRouter.patientOrigin+'/cmmuseum/list';
        //console.log(url);
        $.ajax({
            url:url,
            type:'GET',
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    data.cmmuseums.map(item=>{
                        if(item._id===id){
                            this.setState({
                                storeName:item.name
                            })
                        }
                    })
                }
            },
            error:err=>{

            }
        });
    }
    //开始治疗
    handleStartTraige(record){
        let url=allRouter.patientOrigin+'/surgicalTreatment/modification';
        $.ajax({
            url:url,
            type:'POST',
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                order_id:record.orderID,
                index:record.index,
                data:JSON.stringify({p_name:record.p_name,serveState:2,})
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    this.getPatientOrders(this.state.data1,this.state.data1);
                }
            },
            error:err=>{

            }
        });
    }
    //完成治疗
    handleCompleteTraige(record){
        Modal.confirm({
            title: '完成治疗',
            content: '治疗次数将减少一次，是否确定治疗？',
            cancelText:'取消',
            okText:'确定',
            onCancel: () => { },
            onOk: () => {
                let url=allRouter.patientOrigin+'/surgicalTreatment/modification';
                $.ajax({
                    url:url,
                    type:'POST',
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        order_id:record.orderID,
                        index:record.index,
                        data:JSON.stringify({p_name:record.p_name,p_servedNumber:record.p_servedNumber+1,serveState:0,})
                    },
                    success:data=>{
                        console.log(data);
                        if(data.code===200){
                            this.getPatientOrders(this.state.data1,this.state.data1);
                        }
                    },
                    error:err=>{

                    }
                });
            }
        })

    }
    justFunction(){}
    render() {
        const { patientInfo } = this.state;
        const columns = [
            {
            title: '服务名称',
            dataIndex: 'p_name',
            width:300,
        }, {
            title: '服务次数',
            width: 100,
            render:(text,record)=><span>{record.p_servedNumber+'/'+record.p_Number}</span>
        }, {
            title: '处理医生',
            dataIndex: 'p_doctor',
            width: 100,
        }, {
            title: '付费状态',
            dataIndex: 'p_paystate',
            width: 100,
            render: (text,record)=><span style={{color:text===1?'#ff0000':text===2?'43b1a5':''}}>{text===1?'未付费':text===2?'已付费':''}</span>
        }, {
            title: '付费金额',
            dataIndex: 'p_money',
            width:100,
        }, {
            title: '操作',
            width:100,
            dataIndex:'index',
            render: (text,record) =>
                <Button
                    disabled={(record.isTraiging===4||record.isTraiging===3||record.isTraiging===5)?true:false}
                    style={{background:(record.isTraiging===1?'#43B1A5':record.isTraiging===2?'#0099CC':record.isTraiging===3?'#FF9900':'#ddd'),color:'#fff'}}
                    onClick={record.isTraiging===1?this.handleStartTraige.bind(this,record):record.isTraiging===2?
                        this.handleCompleteTraige.bind(this,record):
                        this.justFunction}>
                    {record.isTraiging===2?'完成治疗':record.isTraiging===3?'已完成':record.isTraiging===5?'已退费':record.isTraiging===4?'未付费':'开始治疗'}
                    </Button>
        }];
        return (
            <div className='container assistant-therapy-detail'>
                <div className='btnBox'>
                    <span className="show-template">
                        <span>*外科治疗</span>
                    </span>
                    <div className='role-manage-box-search my-clear-fix employee-manage-box-search'>
                        <div className='addetd-z employee-manage-search'>
                            <DatePicker style={{width:'300px'}}
                                        disabledDate={(val) => this.disabledDate(val)}
                                        placeholder= '请选择日期'
                                        onChange={this.changeDate.bind(this)}
                                        format='YYYY-MM-DD'
                                        value={this.state.date}
                            />
                        </div>
                    </div>
                </div>
                <div className='box'>
                    <div className='patientinfo'>
                        <img src={require('../../../images/patientDefault.png')} className="default-img"/>
                        <h6>{patientInfo.username}</h6>
                        <p>{patientInfo.userphone}</p>
                        <div className='patientinfoa'>
                            <p>性别：{patientInfo.usersex}</p>
                            <p>年龄：{(new Date().getFullYear() - (patientInfo.userbirthday ? patientInfo.userbirthday.slice(0, 4) : 1)) + '岁'}</p>
                            <p>婚配：{patientInfo.usermarriage}</p>
                            <p>身高：{patientInfo.signmes ? patientInfo.signmes[0].height === 0 ? '' : patientInfo.signmes[0].height + 'cm' : ''}</p>
                            <p>脉搏：{patientInfo.medica?patientInfo.medica.length!==0?patientInfo.medica[0].signmes?patientInfo.medica[0].signmes.pulse+'次/每分钟':'':'':''}</p>
                            <p>呼吸：{patientInfo.medica?patientInfo.medica.length!==0?patientInfo.medica[0].signmes?patientInfo.medica[0].signmes.breathe+'次/每分钟':'':'':''}</p>
                            <p>血压：{patientInfo.medica?patientInfo.medica.length!==0?patientInfo.medica[0].signmes?patientInfo.medica[0].signmes.bloodpressure+'mmHg':'':'':''}</p>
                            <p>过敏史：{patientInfo.medica?patientInfo.medica.length!==0?patientInfo.medica[0].irritability:'':''}</p>
                        </div>
                    </div>
                    <div className='patientinfo1' style={{ flex: 1 }}>
                        {this.state.allOrderDetails.length?
                            <Collapse accordion defaultActiveKey="0">
                            {this.state.allOrderDetails.length?this.state.allOrderDetails.map(item=>{
                                return <Panel  header={<div className="clearfix caozuo"><h4>{item.department+'-初诊-'+item.consumptiontime+'-'+this.state.storeName}</h4></div>} key={item.index}>
                                    <div className="jzxx">
                                        <Table dataSource={item.chargeschedule} columns={columns} bordered  pagination={false} rowKey="index"/>
                                    </div>
                                </Panel>
                            }):''}
                        </Collapse>: <span>{this.state.data1?this.state.data1+':该日期下无该患者订单':'今天无该患者订单'}</span>}
                    </div>
                </div>



            </div>
        );
    }
}

export default AssistantTherapyDetails;